package com.stylefeng.guns.modular.wehcat.api;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.config.redis.RedisUtil;
import com.stylefeng.guns.modular.wehcat.dto.BizWechatReceivedMessage;
import com.stylefeng.guns.modular.wehcat.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

@Slf4j
@Component
public class WechatApi {

	@Resource
	private RedisUtil redisUtil;
	// 7200失效
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	// 刷新token
	private static  final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
	// 检验授权凭证（access_token）是否有效 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
	//private static final String CHECK_REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID";
	// 获取code code说明 ：
	// code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
	private static final String CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo#wechat_redirect";
	// 获取用户基本信息（包括UnionID机制）
	// access_token 是 调用接口凭证
	// openid 是 普通用户的标识，对当前公众号唯一
	// lang 否 返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
//	private static final String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	private static final String TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	//获取openId的
	private static  final  String  OPENID_URL="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	/**
	 * <pre>
	 * 获取CODE
	 * &#64;
	 * return
	 * </pre>
	 * @return
	 */
	public  String  getCode() {
		log.info("==============开始获取code===================");
		try {
			String url=CODE_URL.replace("APPID", redisUtil.get("wx-appid").toString())
					.replace("REDIRECT_URI", URLEncoder.encode(redisUtil.get("REDIRECT_URI").toString(),"UTF-8"));
			log.info("重定向的地址是:【{}】  响应信息:[{}]",url);
			return  url;
		} catch (Exception e) {
			log.error("获取code失败",e);
		}
		return null;
	}

	public String  getOpenId(String code) {
		String openIdUrl=OPENID_URL.replace("APPID", redisUtil.get("wx-appid").toString())
		.replace("SECRET", redisUtil.get("wx-appsecret").toString())
		.replace("CODE", code);
		JSONObject jsonObject= HttpClientUtils.httpGet(openIdUrl);
		log.info("调用获取OpenId的接口返回结果为：{}",jsonObject);
		if(jsonObject!=null) {
			//过期时间提前2秒，以便定时刷新token信息
			String openid=jsonObject.getString("openid");
			return openid;
		}
		return null;
	}
	
	
	/**
	 * 获取token
	 * 
	 * @return
	 */
	public String getAccessToken() {
		String json = get(ACCESS_TOKEN_URL.replace("APPID", redisUtil.get("wx-appid").toString()).replace("APPSECRET",
				redisUtil.get("wx-appsecret").toString()));
		JSONObject jsonObject = JSONObject.parseObject(json);
		String token = jsonObject.getString("access_token");
		return token;
	}

	/**
	 * 发送模板信息
	 */
	public void sendTemplateMessage(String OpenId,  String productName, String money, String remark,String templateId) {
		String template_message_url = TEMPLATE_MESSAGE_URL.replace("ACCESS_TOKEN",
				redisUtil.get("access_token").toString());
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		String date = format.format(System.currentTimeMillis());
		String data = "{\r\n" + 
				"    \"touser\":\""+OpenId+"\",\r\n" + 
				"    \"template_id\":\""+templateId+"\",\r\n" + 
				"    \"topcolor\":\"#FF0000\",\r\n" + 
				"    \"data\":{\r\n" + 
				"			\"first\": {\r\n" + 
				"                \"value\":\"恭喜您已购买成功。\",\r\n" + 
				"                \"color\":\"#173177\"\r\n" + 
				"            },\r\n" + 
				"            \"keyword1\": {\r\n" + 
				"                \"value\":\""+money+"\",\r\n" + 
				"                \"color\":\"#173177\"\r\n" + 
				"            },\r\n" + 
				"            \"keyword2\":{\r\n" + 
				"                \"value\":\""+productName+"\",\r\n" + 
				"                \"color\":\"#173177\"\r\n" + 
				"            },\r\n" + 
				"            \"keyword3\": {\r\n" + 
				"                \"value\":\""+date+"\",\r\n" + 
				"                \"color\":\"#173177\"\r\n" + 
				"            },\r\n" + 
				"            \"remark\":{\r\n" + 
				"                \"value\":\""+remark+"\",\r\n" + 
				"                \"color\":\"#173177\"\r\n" + 
				"            }\r\n" + 
				"    }\r\n" + 
				"}";
//		String  str="{\r\n" + 
//				"    \"touser\":\"oMCkl1iUh_lOQnkkSvpTyjVu6Sdc\",\r\n" + 
//				"    \"template_id\":\"c9JliVtZuHy5YgpP5VNAHPVuamct8J0Gdy0n1E2m2f8\",\r\n" + 
//				"    \"topcolor\":\"#FF0000\",\r\n" + 
//				"    \"data\":{\r\n" + 
//				"			\"Title\": {\r\n" + 
//				"                \"value\":\"恭喜您已购买成功。\",\r\n" + 
//				"                \"color\":\"#173177\"\r\n" + 
//				"            },\r\n" + 
//				"            \"User\": {\r\n" + 
//				"                \"value\":\"田先生\",\r\n" + 
//				"                \"color\":\"#173177\"\r\n" + 
//				"            },\r\n" + 
//				"            \"Date\":{\r\n" + 
//				"                \"value\":\"06月07日 19时24分\",\r\n" + 
//				"                \"color\":\"#173177\"\r\n" + 
//				"            },\r\n" + 
//				"            \"Product\": {\r\n" + 
//				"                \"value\":\"全身精油按摩\",\r\n" + 
//				"                \"color\":\"#173177\"\r\n" + 
//				"            },\r\n" + 
//				"            \"Money\":{\r\n" + 
//				"                \"value\":\"人民币260.00元\",\r\n" + 
//				"                \"color\":\"#173177\"\r\n" + 
//				"            }\r\n" + 
//				"    }\r\n" + 
//				"}";
		HttpClientUtils.httpPost(template_message_url, data);
	}

	/**
	 * 向指定的代码发送Url
	 * 
	 * @param url
	 * @return
	 */
	public static String get(String url) {
		try {
			URL urlObj = new URL(url);
			URLConnection connection = urlObj.openConnection();
			InputStream in = connection.getInputStream();
			byte[] b = new byte[1024];
			int len;
			StringBuffer sb = new StringBuffer();
			while ((len = in.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			return sb.toString();
		} catch (Exception e) {
			log.error("获取url失败", e);
		}
		return null;
	}

//	public JSONObject getCode() {
//		String REDIRECT_URI = "http://www.tyler.org.cn/wechat/getCode.asp";
//		String url = urlEnodeUTF8(REDIRECT_URI);
//		return HttpClientUtils
//				.httpGet(CODE_URL.replace("APPID", redisUtil.get("wx-appid").toString()).replace("REDIRECT_URI", url));
//	}

	/**
	 * <pre>
	 * <p>URLEncoder 编码</p>
	 * <p>@param  str</p>
	 * <p>@return</p>
	 * </pre>
	 */
	public static String urlEnodeUTF8(String str) {
		String result = str;
		try {
			result = URLEncoder.encode(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 自动聊天回复消息
	 * @param message
	 * @param response 
	 */
	public void replyMessage(BizWechatReceivedMessage message, HttpServletResponse response) {
    	PrintWriter writer=null;
		try {
//			String  replyUrl="http://api.qingyunke.com/api.php?key=free&appid=0&msg="+message.getContent();
			String  replyUrl="http://i.itpk.cn/api.php?question="+message.getContent()+"&api_key=802a6b065aef07f87ad44abc8f2fc40d&api_secret=g7p94fm88iu8";
	    	String contant=HttpClientUtils.httpGetStr(replyUrl);
	    	String  replyContant="<xml>"
	    			+"<ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
	    			+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
	    			+"<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>"
	    			+"<MsgType><![CDATA[text]]></MsgType>"
	    			+"<Content><![CDATA["+contant+"]]></Content>"
	    			+"</xml>";
			writer = response.getWriter();
			writer.println(replyContant);
			writer.flush();
		} catch (IOException e) {
			log.error("自动回复消息失败",e);
		}finally {
			if(writer!=null)
				writer.close();
		}
    	
    	
    	
	}
}
